"""
酶抑制剂清除率计算示例

该脚本演示如何使用inhibition_clearance.py模块计算
四种不同抑制模式下的药物清除率变化

作者：BlackCat@CPPO
版本：1.0.0
"""

import numpy as np
import matplotlib.pyplot as plt
from src.elimination.inhibition_clearance import InhibitionClearanceCalculator, InhibitionModelIntegrator

def example_competitive_inhibition():
    """
    竞争性抑制示例
    """
    print("=== 竞争性抑制示例 ===")
    
    # 设置参数
    parameters = {
        'Vmax': 100.0,      # μmol/min/mg蛋白
        'Km': 10.0,         # μM
        'Clint': 10.0,      # L/h/kg
        'fu': 0.1,          # 游离分数
        'BP': 1.0,          # 血液-血浆浓度比
        'Ki': 1.0,          # 抑制常数 (μM)
        'liver_weight': 1.8,    # kg
        'microsomal_protein': 45.0,  # mg/g肝脏
        'liver_flow': 1.35      # L/h
    }
    
    # 创建计算器
    calculator = InhibitionClearanceCalculator(parameters)
    
    # 不同抑制剂浓度下的清除率
    inhibitor_concentrations = [0, 0.1, 0.5, 1.0, 2.0, 5.0, 10.0]
    substrate_concentration = 10.0  # μM
    
    results = []
    for conc in inhibitor_concentrations:
        result = calculator.calculate_competitive_inhibition_clearance(
            substrate_concentration, conc)
        results.append({
            'inhibitor_concentration': conc,
            'hepatic_clearance': result['hepatic_clearance'],
            'inhibition_ratio': result['inhibition_ratio'][0]
        })
    
    print("抑制剂浓度 (μM) | 肝脏清除率 (L/h) | 抑制比例 (%)")
    print("-" * 50)
    for r in results:
        clearance = float(np.array(r['hepatic_clearance']).flatten()[0])
        inhibition_ratio = float(np.array(r['inhibition_ratio']).flatten()[0])
        print(f"{r['inhibitor_concentration']:>12.1f} | {clearance:>15.3f} | {inhibition_ratio*100:>12.1f}%")
    
    return results

def example_all_inhibition_modes():
    """
    所有四种抑制模式对比示例
    """
    print("\n=== 四种抑制模式对比示例 ===")
    
    # 设置参数
    parameters = {
        'Vmax': 100.0,
        'Km': 10.0,
        'Clint': 10.0,
        'fu': 0.1,
        'BP': 1.0,
        'Ki': 1.0,
        'alpha': 2.0,   # 混合型抑制参数
        'beta': 0.5,    # 混合型抑制参数
        'liver_weight': 1.8,
        'microsomal_protein': 45.0,
        'liver_flow': 1.35
    }
    
    # 创建计算器
    calculator = InhibitionClearanceCalculator(parameters)
    
    # 计算所有模式
    substrate_concentration = 10.0
    inhibitor_concentration = 2.0
    
    all_results = calculator.calculate_all_inhibition_modes(
        substrate_concentration, inhibitor_concentration)
    
    print(f"底物浓度: {substrate_concentration} μM")
    print(f"抑制剂浓度: {inhibitor_concentration} μM")
    print("-" * 50)
    
    modes = ['control', 'competitive', 'noncompetitive', 'uncompetitive', 'mixed']
    print("抑制模式       | 肝脏清除率 (L/h) | 抑制比例 (%)")
    print("-" * 50)
    
    for mode in modes:
        clearance = float(np.array(all_results[mode]['hepatic_clearance']).flatten()[0])
        
        if mode == 'control':
            inhibition_ratio = 0.0
            print(f"{mode:>12} | {clearance:>15.3f} | {'':>12}")
        else:
            inhibition_ratio = float(np.array(all_results['summary']['inhibition_ratios'][mode]).flatten()[0])
            print(f"{mode:>12} | {clearance:>15.3f} | {inhibition_ratio*100:>12.1f}%")
    
    return all_results

def example_concentration_response():
    """
    浓度-响应关系示例
    """
    print("\n=== 浓度-响应关系示例 ===")
    
    # 设置参数
    parameters = {
        'Vmax': 100.0,
        'Km': 10.0,
        'Clint': 10.0,
        'fu': 0.1,
        'BP': 1.0,
        'Ki': 1.0,
        'alpha': 2.0,
        'beta': 0.5,
        'liver_weight': 1.8,
        'microsomal_protein': 45.0,
        'liver_flow': 1.35
    }
    
    # 创建计算器
    calculator = InhibitionClearanceCalculator(parameters)
    
    # 生成抑制剂浓度范围
    inhibitor_concentrations = np.logspace(-2, 2, 50)  # 0.01 to 100 μM
    substrate_concentration = 10.0
    
    # 计算各模式的抑制比例
    competitive_inhibition = []
    noncompetitive_inhibition = []
    uncompetitive_inhibition = []
    mixed_inhibition = []
    
    for conc in inhibitor_concentrations:
        # 计算各抑制模式
        comp_result = calculator.calculate_competitive_inhibition_clearance(
            substrate_concentration, conc)
        noncomp_result = calculator.calculate_noncompetitive_inhibition_clearance(
            substrate_concentration, conc)
        uncomp_result = calculator.calculate_uncompetitive_inhibition_clearance(
            substrate_concentration, conc)
        mixed_result = calculator.calculate_mixed_inhibition_clearance(
            substrate_concentration, conc)
        
        competitive_inhibition.append(comp_result['inhibition_ratio'][0])
        noncompetitive_inhibition.append(noncomp_result['inhibition_ratio'][0])
        uncompetitive_inhibition.append(uncomp_result['inhibition_ratio'][0])
        mixed_inhibition.append(mixed_result['inhibition_ratio'][0])
    
    # 转换为numpy数组
    competitive_inhibition = np.array(competitive_inhibition)
    noncompetitive_inhibition = np.array(noncompetitive_inhibition)
    uncompetitive_inhibition = np.array(uncompetitive_inhibition)
    mixed_inhibition = np.array(mixed_inhibition)
    
    # 打印关键数据点
    print("抑制剂浓度 (μM) | 竞争性抑制(%) | 非竞争性抑制(%) | 反竞争性抑制(%) | 混合型抑制(%)")
    print("-" * 90)
    
    key_concentrations = [0.1, 0.5, 1.0, 2.0, 5.0, 10.0]
    for conc in key_concentrations:
        idx = np.argmin(np.abs(inhibitor_concentrations - conc))
        comp_val = float(competitive_inhibition[idx]) * 100
        noncomp_val = float(noncompetitive_inhibition[idx]) * 100
        uncomp_val = float(uncompetitive_inhibition[idx]) * 100
        mixed_val = float(mixed_inhibition[idx]) * 100
        
        print(f"{float(inhibitor_concentrations[idx]):>15.2f} | {comp_val:>14.1f} | "
              f"{noncomp_val:>16.1f} | {uncomp_val:>16.1f} | {mixed_val:>13.1f}")
    
    return {
        'inhibitor_concentrations': inhibitor_concentrations,
        'competitive_inhibition': competitive_inhibition,
        'noncompetitive_inhibition': noncompetitive_inhibition,
        'uncompetitive_inhibition': uncompetitive_inhibition,
        'mixed_inhibition': mixed_inhibition
    }

def plot_inhibition_curves():
    """
    绘制抑制曲线
    """
    try:
        import matplotlib.pyplot as plt
        
        # 设置参数
        parameters = {
            'Vmax': 100.0,
            'Km': 10.0,
            'Clint': 10.0,
            'fu': 0.1,
            'BP': 1.0,
            'Ki': 1.0,
            'alpha': 2.0,
            'beta': 0.5,
            'liver_weight': 1.8,
            'microsomal_protein': 45.0,
            'liver_flow': 1.35
        }
        
        calculator = InhibitionClearanceCalculator(parameters)
        
        # 生成数据
        inhibitor_concentrations = np.logspace(-2, 2, 50)
        substrate_concentration = 10.0
        
        results = example_concentration_response()
        
        # 创建图表
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
        
        # 抑制比例图
        ax1.semilogx(results['inhibitor_concentrations'], 
                    results['competitive_inhibition']*100, 
                    'b-', label='竞争性抑制', linewidth=2)
        ax1.semilogx(results['inhibitor_concentrations'], 
                    results['noncompetitive_inhibition']*100, 
                    'r-', label='非竞争性抑制', linewidth=2)
        ax1.semilogx(results['inhibitor_concentrations'], 
                    results['uncompetitive_inhibition']*100, 
                    'g-', label='反竞争性抑制', linewidth=2)
        ax1.semilogx(results['inhibitor_concentrations'], 
                    results['mixed_inhibition']*100, 
                    'm-', label='混合型抑制', linewidth=2)
        
        ax1.set_xlabel('抑制剂浓度 (μM)')
        ax1.set_ylabel('抑制比例 (%)')
        ax1.set_title('酶抑制浓度-响应关系')
        ax1.legend()
        ax1.grid(True, alpha=0.3)
        
        # 清除率图
        control_clearance = calculator.calculate_control_clearance(substrate_concentration)['hepatic_clearance']
        
        ax2.semilogx(results['inhibitor_concentrations'], 
                    control_clearance * (1 - results['competitive_inhibition']), 
                    'b-', label='竞争性抑制', linewidth=2)
        ax2.semilogx(results['inhibitor_concentrations'], 
                    control_clearance * (1 - results['noncompetitive_inhibition']), 
                    'r-', label='非竞争性抑制', linewidth=2)
        ax2.semilogx(results['inhibitor_concentrations'], 
                    control_clearance * (1 - results['uncompetitive_inhibition']), 
                    'g-', label='反竞争性抑制', linewidth=2)
        ax2.semilogx(results['inhibitor_concentrations'], 
                    control_clearance * (1 - results['mixed_inhibition']), 
                    'm-', label='混合型抑制', linewidth=2)
        
        ax2.axhline(y=control_clearance, color='k', linestyle='--', label='对照组')
        ax2.set_xlabel('抑制剂浓度 (μM)')
        ax2.set_ylabel('肝脏清除率 (L/h)')
        ax2.set_title('酶抑制对肝脏清除率的影响')
        ax2.legend()
        ax2.grid(True, alpha=0.3)
        
        plt.tight_layout()
        plt.savefig('/home/jiaxiaohan/PBPK_Modeling_System/output/inhibition_curves.png', 
                   dpi=300, bbox_inches='tight')
        plt.show()
        
        print("\n抑制曲线已保存至: output/inhibition_curves.png")
        
    except ImportError:
        print("\n警告: matplotlib未安装，无法绘制图表")
        print("请安装matplotlib: pip install matplotlib")

if __name__ == "__main__":
    # 运行示例
    print("酶抑制剂清除率计算示例")
    print("=" * 50)
    
    # 运行示例1：竞争性抑制
    example1_results = example_competitive_inhibition()
    
    # 运行示例2：所有抑制模式对比
    example2_results = example_all_inhibition_modes()
    
    # 运行示例3：浓度-响应关系
    example3_results = example_concentration_response()
    
    # 绘制图表
    plot_inhibition_curves()
    
    print("\n" + "=" * 50)
    print("所有示例运行完成！")